package com.nginx.web.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nginx.web.domain.LoginRequest;
import com.nginx.web.entity.User;
import com.nginx.web.service.UserService;
import com.nginx.web.util.ApiUtil;
import com.nginx.web.util.Result;
import com.nginx.web.util.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xxy
 * @Date 2024/9/2
 */
@Api(tags = "登录管理")
@RequestMapping("/admin")
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value="登录")
    public Result login(LoginRequest loginRequest){
        if (StringUtils.isEmpty(loginRequest.getUserName())) {
            ApiUtil.back(ResultEnum.ERROR, "用户名不能为空");
        }
        if (StringUtils.isEmpty(loginRequest.getPassWord())) {
            ApiUtil.back(ResultEnum.ERROR, "密码不能为空");
        }
        User user = userService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, loginRequest.getUserName())
                );
        if (user == null) {
            ApiUtil.back(ResultEnum.ERROR, "用户名不正确");
        }

        if (!StrUtil.equals(loginRequest.getPassWord() , user.getPassword()) ) {
            ApiUtil.back(ResultEnum.ERROR, "用户名或密码不正确");
        }
        StpUtil.login(user.getId());
        Map<Object, Object> resultMap = new HashMap<>();
        resultMap.put("userInfo", user);
        resultMap.put("tokenInfo", StpUtil.getTokenInfo());
        return Result.success(resultMap);
    }

}
